<template>
  <div class="personalHome">
    <div class="info">
      <div class="img-box fl">
        <img :src="form.avatar ? form.avatar:'@/assets/images/default.jpg'" width="80" height="100">
      </div>
      <div class="personinfo">
        <p><strong>欢迎您：{{initData.info.userName}}&nbsp;&nbsp;&nbsp;&nbsp;<span style="margin-left: 10px;">性别：{{((key)=>{
          switch(key){
            case '1': return '男';break;
            case '0': return '女';break;
            default: return '未知';break;
          }
          })(initData.info.sex)}}</span></strong></p>
        <p><span>注册时间：{{$util.formDate(initData.info.createdAt)}}</span></p>
        <p>
          <span>手机号码：
            <em>{{initData.info.phone}}</em></span><span>
            <!-- <a href="javascript:;">更换手机</a> -->
          </span>
        </p>
      </div>
    </div>
    <div class="tabs">
      <h3>
        <span :class="activeTab==0 ? 'active' : ''" @click="activeTab = 0">个人资料</span>
        <span :class="activeTab==1 ? 'active' : ''" @click="activeTab = 1">修改密码</span>
      </h3>
      <div class="form1" v-show="activeTab==0">
        <el-form ref="form" :model="form" label-width="100px" :rules="rules">
          <el-form-item label="昵称" prop="userName">
            <el-input v-model="form.userName"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="form.realName" :disabled="isReal"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="idCardNo">
            <el-input v-model="form.idCardNo" :disabled="isReal"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio-button label="1">男</el-radio-button>
              <el-radio-button label="0">女</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" disabled></el-input>
            <!-- <el-button type="primary" class="fr" @click="sendCode" :disabled="isSend">{{text}}</el-button> -->
          </el-form-item>
          <!-- <el-form-item label="邮箱验证码" prop="code">
            <el-input v-model="form.code"></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="onSubmit">立即保存</el-button>
            <span class="tip-updated">*更新时间: {{$util.formDate(initData.info.updatedAt)}}</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="form2" v-show="activeTab==1">
        <el-form ref="form2" :model="form2" label-width="100px" :rules="rules2">
          <el-form-item label="旧密码" prop="o_pw">
            <el-input v-model="form2.o_pw" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="n_pw">
            <el-input v-model="form2.n_pw" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="a_pw">
            <el-input v-model="form2.a_pw" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="onChange">立即修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "personalHome",
  data() {
    return {
      isAble: true,
      initData: {
        info: {},
      },
      activeTab: 0,
      isReal: false,
      form: {
        userName: '',
        realName: '',
        idCardNo: '',
        sex: '',
        email: '',
        avatar: ''
        // code: '',
      },
      form2: {
        o_pw: '',
        n_pw: '',
        a_pw: '',
      },
      rules: {
        userName: [{ required: true, validator: this.validUsername, trigger: "blur" }],
        realName: [{ validator: this.validRealname, trigger: "blur" }],
        idCardNo: [{ validator: this.validIdCardNo, trigger: "blur" }],
        sex: [{ required: true, validator: this.validSex, trigger: "change" }],
      },
      rules2: {
        o_pw: [{ validator: this.validOpw, trigger: "blur" }],
        n_pw: [{ validator: this.validNpw, trigger: "blur" }],
        a_pw: [{ validator: this.validApw, trigger: "blur" }],
      },
      // 验证码id
      codeId: '',
      text: '获取验证码',
      isSend: false,
    }
  },
  created() {
    this.init();
    this.getUserInfo();
  },
  methods: {
    init() {

    },
    //获取用户信息
    getUserInfo() {
      this.axios({
        method: "GET",
        url: this.baseUrl + "/getUserInfo",
        params: {
          userId: this.$cookies.get('__ui')
        }
      })
        .then((res) => {
          console.log("res ==> ", res);

          if (res.data.code == 1034) {
            this.isLogin = false;
          }

          if (res.data.code == 1040) {
            this.initData.info = res.data.data.result[0];
            console.log(this.initData.info)
            this.form = {
              userName: res.data.data.result[0].userName,
              realName: res.data.data.result[0].realName,
              idCardNo: res.data.data.result[0].idCardNo,
              sex: res.data.data.result[0].sex,
              email: res.data.data.result[0].email,
              avatar: res.data.data.url + res.data.data.result[0].avatar,
              // code: '',
            }
            this.form.idCardNo = this.form.idCardNo == null || this.form.idCardNo == 'null' ? '' : this.form.idCardNo;
            this.form.realName = this.form.realName == null || this.form.realName == 'null' ? '' : this.form.realName;
            if (this.form.idCardNo != '' && this.form.realName != '') {
              this.isReal = true;
            } else {
              this.isReal = false;
            }

          } else {
            // this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log("err ==> ", err);
        });
    },
    // 保存信息
    onSubmit() {
      if (!this.isAble) {// 防止重复提交
        return;
      }
      console.log('form1==>', this.form)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.idCardNo == '' && this.form.realName != '') {
            this.$message.warning('请输入身份证号!')
            return;
          } else if (this.form.idCardNo != '' && this.form.realName == '') {
            this.$message.warning('请输入真实姓名!')
            return;
          } else if (this.form.idCardNo != '' && this.form.realName != '') {
            if (this.form.idCardNo.charAt(this.form.idCardNo.length - 2) % 2 == this.form.sex) {
              this.$message.warning('身份证号与性别不符')
              return;
            }
          }
          // 发起修改请求
          this.isAble = false;// 防止重复提交
          this.axios({
            method: 'post',
            url: this.baseUrl + '/editUser',
            data: {
              userName: this.form.userName,
              realName: this.form.realName,
              idCardNo: this.form.idCardNo,
              sex: this.form.sex,
            }
          }).then(res => {
            console.log('edit res==>', res)
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              setTimeout(() => {
                this.$router.go(0)
              }, 1000);
            } else {
              this.$message.error(res.data.msg)
              this.isAble = true;
            }
          }).catch(err => {
            console.log("err ==> ", err);
            this.$message.success(err)
          })


        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 修改密码
    onChange() {
      if (!this.isAble) {// 防止重复提交
        return;
      }
      console.log('form2==>', this.form2)
      this.$refs['form2'].validate((valid) => {
        if (valid) {
          // 发起修改请求
          this.isAble = false;// 防止重复提交
          this.axios({
            method: 'post',
            url: this.baseUrl + '/editUser',
            data: {
              o_pw: this.form2.o_pw,
              password: this.form2.a_pw,
            }
          }).then(res => {
            console.log('edit res==>', res)
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              this.form2 = {
                o_pw: '',
                n_pw: '',
                a_pw: ''
              };
            } else {
              this.$message.error(res.data.msg)
            }
            this.isAble = true;
          }).catch(err => {
            console.log("err ==> ", err);
            this.$message.error(err)
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // -----------------------------------------------------------
    // 验证网站昵称
    validUsername(rule, value, callback) {
      if (value == '') {
        callback(Error("请输入网站昵称"));
      } else {
        callback();
      }
    },
    // 验证真实姓名
    validRealname(rule, value, callback) {
      if (!value) {
        // callback(new Error("姓名不能为空"));
        callback();
      } else if (!/^[\u4e00-\u9fa5·]{2,5}/.test(value)) {
        callback(new Error("姓名有误!"));
      } else {
        callback();
      }
    },
    // 验证身份证
    validIdCardNo(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        let reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
        if (!reg.test(value)) {
          callback(new Error("身份证有误!"));
        } else {
          callback();
        }
      }
    },
    // 验证性别 
    validSex(rule, value, callback) {
      if (value == '2') {
        callback(Error("请选择性别"));
      } else {
        callback();
      }
    },

    // 验证密码(首字符为字母, 字母数字_组合, 6-16位)
    validOpw(rule, value, callback) {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    },
    // 验证新密码
    validNpw(rule, value, callback) {
      if (!value) {
        callback(new Error("新密码不能为空"));
      } else {
        // let reg = /^[A-Za-z]\w{5,15}$/;
        // if (!reg.test(value)) {
        //   callback(new Error("密码必须以字母开头，可包含字母数字_"));
        // } else {
        //   callback();
        // }
        callback();
      }
    },
    // 验证确认密码
    validApw(rule, value, callback) {
      if (this.form2.n_pw === '') {
        callback('确认密码不能为空');
      } else {
        if (value !== this.form2.n_pw) {
          callback(new Error("两次密码不一样"));
        } else {
          callback();
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
@theme: #00b16a;
.personalHome {
  .info {
    margin-bottom: 20px;
    .img-box {
      width: 80px;
      height: 100px;
      margin-right: 20px;
    }
    .personinfo {
      > p {
        margin-bottom: 20px;
        a {
          text-decoration: underline;
          margin-left: 5px;
          &:hover {
            color: @theme;
          }
        }
      }
    }
  }

  .tabs {
    h3 {
      width: 100%;
      padding-bottom: 2px;
      border-bottom: 2px solid @theme;
      margin-bottom: 20px;
      span {
        display: inline-block;
        cursor: pointer;
        width: 100px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        color: @theme;
        &.active {
          color: #fff;
          background-color: @theme;
        }
      }
    }
    .form1,
    .form2 {
      padding: 0 200px;

      .tip-updated {
        color: #999999;
      }
    }
  }
}
</style>